package com.kotlin.book.adapter

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.book.activity.DetailActivity
import com.kotlin.book.databinding.ItemShelfListBinding
import com.kotlin.book.entry.Book
import com.kotlin.book.util.Util

class ShelfListItemAdapter(private var itemList: List<Book>) :
    RecyclerView.Adapter<ShelfListItemAdapter.ItemViewHolder>() {

    class ItemViewHolder(itemBinding: ItemShelfListBinding) :
        RecyclerView.ViewHolder(itemBinding.root) {

        val bookName: TextView = itemBinding.bookName
        val text1: TextView = itemBinding.text1
        val bookImage: ImageView = itemBinding.bookImage
        var text2 = itemBinding.text2
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val binding =
            ItemShelfListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ItemViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val item = itemList[position]
        holder.bookName.text = item.name
        holder.text1.text = item.author
        holder.text2.text = item.type

        Util.getImage(item.pic, holder.bookImage, holder.itemView.context)

        holder.itemView.setOnClickListener {
            // 页面跳转
            val intent = Intent(holder.itemView.context, DetailActivity::class.java)
            val bundle = Bundle()
            // 传参
            bundle.putInt("id", item.id)
            intent.putExtras(bundle)
            holder.itemView.context.startActivity(intent)
        }
    }

    override fun getItemCount(): Int {
        return itemList.size
    }
}